"""
闲鱼订单详情获取工具
基于Playwright实现订单详情页面访问和数据提取
"""

import asyncio
import time
import sys
import os
import json
import urllib.parse
import hashlib
import aiohttp
from typing import Optional, Dict, Any
from playwright.async_api import async_playwright, Browser, BrowserContext, Page
from loguru import logger

# 修复Docker环境中的asyncio事件循环策略问题
if sys.platform.startswith('linux') or os.getenv('DOCKER_ENV'):
    try:
        # 在Linux/Docker环境中设置事件循环策略
        asyncio.set_event_loop_policy(asyncio.DefaultEventLoopPolicy())
    except Exception as e:
        logger.warning(f"设置事件循环策略失败: {e}")

# 确保在Docker环境中使用正确的事件循环
if os.getenv('DOCKER_ENV'):
    try:
        # 强制使用SelectorEventLoop（在Docker中更稳定）
        if hasattr(asyncio, 'SelectorEventLoop'):
            loop = asyncio.SelectorEventLoop()
            asyncio.set_event_loop(loop)
    except Exception as e:
        logger.warning(f"设置SelectorEventLoop失败: {e}")


class OrderDetailFetcher:
    """闲鱼订单详情获取器"""

    def __init__(self, cookie_string: str = None):
        self.browser: Optional[Browser] = None
        self.context: Optional[BrowserContext] = None
        self.page: Optional[Page] = None

        # 请求头配置
        self.headers = {
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-language": "en,zh-CN;q=0.9,zh;q=0.8,ru;q=0.7",
            "cache-control": "no-cache",
            "pragma": "no-cache",
            "priority": "u=0, i",
            "sec-ch-ua": "\"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Google Chrome\";v=\"138\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "same-origin",
            "sec-fetch-user": "?1",
            "upgrade-insecure-requests": "1"
        }

        # Cookie配置 - 支持动态传入
        self.cookie = cookie_string

    async def init_browser(self, headless: bool = True):
        """初始化浏览器"""
        try:
            playwright = await async_playwright().start()
            
            # 启动浏览器（Docker环境优化）
            browser_args = [
                '--no-sandbox',
                '--disable-setuid-sandbox',
                '--disable-dev-shm-usage',
                '--disable-accelerated-2d-canvas',
                '--no-first-run',
                '--no-zygote',
                '--disable-gpu',
                '--disable-background-timer-throttling',
                '--disable-backgrounding-occluded-windows',
                '--disable-renderer-backgrounding',
                '--disable-features=TranslateUI',
                '--disable-ipc-flooding-protection',
                '--disable-extensions',
                '--disable-default-apps',
                '--disable-sync',
                '--disable-translate',
                '--hide-scrollbars',
                '--mute-audio',
                '--no-default-browser-check',
                '--no-pings',
                '--single-process'  # 在Docker中使用单进程模式
            ]

            # 在Docker环境中添加额外参数
            if os.getenv('DOCKER_ENV'):
                browser_args.extend([
                    '--disable-background-networking',
                    '--disable-background-timer-throttling',
                    '--disable-client-side-phishing-detection',
                    '--disable-default-apps',
                    '--disable-hang-monitor',
                    '--disable-popup-blocking',
                    '--disable-prompt-on-repost',
                    '--disable-sync',
                    '--disable-web-resources',
                    '--metrics-recording-only',
                    '--no-first-run',
                    '--safebrowsing-disable-auto-update',
                    '--enable-automation',
                    '--password-store=basic',
                    '--use-mock-keychain'
                ])

            self.browser = await playwright.chromium.launch(
                headless=headless,
                args=browser_args
            )
            
            # 创建浏览器上下文
            self.context = await self.browser.new_context(
                viewport={'width': 1920, 'height': 1080},
                user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36'
            )
            
            # 设置额外的HTTP头
            await self.context.set_extra_http_headers(self.headers)
            
            # 创建页面
            self.page = await self.context.new_page()
            
            # 设置Cookie
            await self._set_cookies()
            
            logger.info("浏览器初始化成功")
            return True
            
        except Exception as e:
            logger.error(f"浏览器初始化失败: {e}")
            return False

    async def _set_cookies(self):
        """设置Cookie"""
        try:
            # 解析Cookie字符串
            cookies = []
            for cookie_pair in self.cookie.split('; '):
                if '=' in cookie_pair:
                    name, value = cookie_pair.split('=', 1)
                    cookies.append({
                        'name': name.strip(),
                        'value': value.strip(),
                        'domain': '.goofish.com',
                        'path': '/'
                    })
            
            # 添加Cookie到上下文
            await self.context.add_cookies(cookies)
            logger.info(f"已设置 {len(cookies)} 个Cookie")
            
        except Exception as e:
            logger.error(f"设置Cookie失败: {e}")

    def _extract_token_from_cookie(self) -> Optional[str]:
        """从Cookie中提取_m_h5_tk token"""
        try:
            if not self.cookie:
                return None
            
            # 查找_m_h5_tk的值
            for cookie_pair in self.cookie.split('; '):
                if '=' in cookie_pair:
                    name, value = cookie_pair.split('=', 1)
                    if name.strip() == '_m_h5_tk':
                        # _m_h5_tk的格式通常是：token_timestamp
                        # 我们只需要token部分（下划线前的部分）
                        token_full = value.strip()
                        if '_' in token_full:
                            token = token_full.split('_')[0]
                            logger.debug(f"从Cookie中提取到token: {token[:10]}...")
                            return token
                        else:
                            logger.debug(f"从Cookie中提取到完整token: {token_full[:10]}...")
                            return token_full
            
            logger.warning("Cookie中未找到_m_h5_tk")
            return None
            
        except Exception as e:
            logger.error(f"从Cookie中提取token失败: {e}")
            return None

    async def fetch_order_detail_via_api(self, order_id: str, timeout: int = 30) -> Optional[Dict[str, Any]]:
        """
        通过API接口获取订单详情
        
        Args:
            order_id: 订单ID
            timeout: 超时时间（秒）
            
        Returns:
            包含订单详情的字典，失败时返回None
        """
        try:
            logger.info(f"开始通过API获取订单详情: {order_id}")
            
            # 构建API请求参数
            api_url = "https://h5api.m.goofish.com/h5/mtop.idle.web.trade.order.detail/1.0/"
            
            # 生成时间戳
            timestamp = str(int(time.time() * 1000))
            
            # 构建请求参数
            params = {
                'jsv': '2.7.2',
                'appKey': '34839810',
                't': timestamp,
                'v': '1.0',
                'type': 'originaljson',
                'accountSite': 'xianyu',
                'dataType': 'json',
                'timeout': '20000',
                'api': 'mtop.idle.web.trade.order.detail',
                'sessionOption': 'AutoLoginOnly',
                'spm_cnt': 'a21ybx.order-detail.0.0'
            }
            
            # 构建data参数
            data_param = {"tid": order_id}
            data_str = json.dumps(data_param, separators=(',', ':'))
            
            # 生成签名（需要从Cookie中提取token）
            token = self._extract_token_from_cookie()
            if token:
                # 使用正确的签名算法：token&timestamp&appKey&data
                sign_str = f"{token}&{params['t']}&{params['appKey']}&{data_str}"
                sign = hashlib.md5(sign_str.encode()).hexdigest()
                params['sign'] = sign
            else:
                logger.warning("无法从Cookie中提取token，使用简化签名")
                # 使用简化的签名方法作为后备
                sign_str = f"&{params['t']}&{params['appKey']}&{data_str}&"
                sign = hashlib.md5(sign_str.encode()).hexdigest()
                params['sign'] = sign
            
            # 构建完整URL
            url_with_params = f"{api_url}?{urllib.parse.urlencode(params)}"
            
            # 构建请求头
            headers = {
                'accept': 'application/json',
                'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
                'content-type': 'application/x-www-form-urlencoded',
                'origin': 'https://www.goofish.com',
                'priority': 'u=1, i',
                'referer': 'https://www.goofish.com/',
                'sec-ch-ua': '"Chromium";v="136", "Microsoft Edge";v="136", "Not.A/Brand";v="99"',
                'sec-ch-ua-mobile': '?0',
                'sec-ch-ua-platform': '"Windows"',
                'sec-fetch-dest': 'empty',
                'sec-fetch-mode': 'cors',
                'sec-fetch-site': 'same-site',
                'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 Edg/136.0.0.0'
            }
            
            # 构建POST数据
            post_data = f"data={urllib.parse.quote(data_str)}"
            
            # 发送API请求
            async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=timeout)) as session:
                # 设置Cookie
                if self.cookie:
                    headers['Cookie'] = self.cookie
                
                async with session.post(url_with_params, headers=headers, data=post_data) as response:
                    if response.status != 200:
                        logger.error(f"API请求失败，状态码: {response.status}")
                        return None
                    
                    response_text = await response.text()
                    logger.debug(f"API响应: {response_text[:500]}...")
                    
                    # 解析JSON响应
                    try:
                        response_data = json.loads(response_text)
                    except json.JSONDecodeError as e:
                        logger.error(f"解析API响应JSON失败: {e}")
                        return None
                    
                    # 检查API响应状态
                    if not response_data.get('ret') or 'SUCCESS' not in str(response_data.get('ret', [])):
                        logger.error(f"API返回错误: {response_data.get('ret', 'Unknown error')}")
                        return None
                    
                    # 提取订单详情数据
                    api_data = response_data.get('data', {})
                    if not api_data:
                        logger.error("API响应中没有数据")
                        return None
                    
                    # 解析订单信息
                    result = self._parse_api_response(order_id, api_data)
                    
                    if result:
                        logger.info(f"通过API获取订单详情成功: {order_id}")
                        return result
                    else:
                        logger.error(f"解析API响应数据失败: {order_id}")
                        return None
                        
        except Exception as e:
            logger.error(f"通过API获取订单详情失败: {e}")
            return None

    def _parse_api_response(self, order_id: str, api_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
        """
        解析API响应数据
        
        Args:
            order_id: 订单ID
            api_data: API返回的数据
            
        Returns:
            解析后的订单详情字典
        """
        try:
            result = {
                'order_id': order_id,
                'timestamp': time.time(),
                'from_cache': False,
                'data_source': 'api',  # 标记数据来源为API
                'raw_api_data': {'data': api_data}  # 保存原始API数据
            }
            
            # 获取组件数据
            components = api_data.get('components', [])
            
            for component in components:
                component_data = component.get('data', {})
                
                # 解析订单信息组件
                if 'orderInfoVO' in component.get('render', ''):
                    # 获取商品信息
                    item_info = component_data.get('itemInfo', {})
                    if item_info:
                        result['item_title'] = item_info.get('title', '')
                        result['item_id'] = str(api_data.get('itemId', ''))
                        result['amount'] = item_info.get('price', '')
                        result['quantity'] = item_info.get('buyAmount', '1')
                        result['sku_info'] = item_info.get('skuInfo', '')
                        
                        # 解析SKU信息
                        sku_info = item_info.get('skuInfo', '')
                        if sku_info and ':' in sku_info:
                            parts = sku_info.split(':', 1)
                            if len(parts) == 2:
                                result['spec_name'] = parts[0].strip()
                                result['spec_value'] = parts[1].strip()
                        
                        # 获取商品图片
                        result['item_image'] = item_info.get('itemMainPictCdnUrl', '')
                    
                    # 获取订单详细信息
                    order_info_list = component_data.get('orderInfoList', [])
                    for info in order_info_list:
                        title = info.get('title', '')
                        value = info.get('value', '')
                        
                        if title == '买家昵称':
                            result['buyer_nick'] = value
                        elif title == '下单时间':
                            result['order_time'] = value
                        elif title == '付款时间':
                            result['pay_time'] = value
                        elif title == '发货时间':
                            result['ship_time'] = value
                        elif title == '收货地址':
                            result['address'] = value
                        elif title == '支付宝交易号':
                            result['alipay_trade_no'] = value
                    
                    # 获取价格信息
                    price_info = component_data.get('priceInfo', {})
                    if price_info:
                        amount_info = price_info.get('amount', {})
                        if amount_info and not result.get('amount'):
                            result['amount'] = amount_info.get('value', '')
                
                # 解析订单状态组件
                elif 'orderStatusVO' in component.get('render', ''):
                    order_status_info = component_data.get('orderStatusInfo', {})
                    if order_status_info:
                        result['order_status_title'] = order_status_info.get('title', '')
            
            # 获取其他基本信息
            result['peer_user_id'] = str(api_data.get('peerUserId', ''))
            result['order_status'] = str(api_data.get('status', ''))
            result['is_seller'] = api_data.get('seller', False)
            
            # 确保必要字段存在
            if not result.get('quantity'):
                result['quantity'] = '1'
            if not result.get('spec_name'):
                result['spec_name'] = ''
            if not result.get('spec_value'):
                result['spec_value'] = ''
            
            # 添加原始API数据到结果中，用于后续状态检查
            result['raw_api_data'] = api_data
            
            logger.info(f"API数据解析成功 - 订单: {order_id}, 商品: {result.get('item_title', '')}, 规格: {result.get('spec_name', '')}: {result.get('spec_value', '')}, 数量: {result.get('quantity', '')}, 金额: {result.get('amount', '')}")
            
            return result
            
        except Exception as e:
            logger.error(f"解析API响应数据异常: {e}")
            return None

    async def fetch_order_detail(self, order_id: str, timeout: int = 30, use_api: bool = True) -> Optional[Dict[str, Any]]:
        """
        获取订单详情（支持API和Playwright两种方式）
        
        Args:
            order_id: 订单ID
            timeout: 超时时间（秒）
            use_api: 是否优先使用API方式，默认True
            
        Returns:
            包含订单详情的字典，失败时返回None
        """
        try:
            # 优先使用API方式获取订单详情
            if use_api:
                logger.info(f"尝试通过API获取订单详情: {order_id}")
                api_result = await self.fetch_order_detail_via_api(order_id, timeout)
                if api_result:
                    logger.info(f"API方式获取订单详情成功: {order_id}")
                    return api_result
                else:
                    logger.warning(f"API方式获取订单详情失败，尝试使用Playwright方式: {order_id}")
            
            # 如果API方式失败或不使用API，则使用Playwright方式
            return await self.fetch_order_detail_via_playwright(order_id, timeout)
            
        except Exception as e:
            logger.error(f"获取订单详情失败: {e}")
            return None

    async def fetch_order_detail_via_playwright(self, order_id: str, timeout: int = 30) -> Optional[Dict[str, Any]]:
        """
        通过Playwright获取订单详情（原有实现）
        
        Args:
            order_id: 订单ID
            timeout: 超时时间（秒）
            
        Returns:
            包含订单详情的字典，失败时返回None
        """
        try:
            if not self.page:
                logger.error("浏览器未初始化")
                return None
            
            # 构建订单详情URL
            url = f"https://www.goofish.com/order-detail?orderId={order_id}&role=seller"
            logger.info(f"开始访问订单详情页面: {url}")
            
            # 访问页面
            response = await self.page.goto(url, wait_until='networkidle', timeout=timeout * 1000)
            
            if not response or response.status != 200:
                logger.error(f"页面访问失败，状态码: {response.status if response else 'None'}")
                return None
            
            logger.info("页面加载成功，等待内容渲染...")
            
            # 等待页面完全加载
            await self.page.wait_for_load_state('networkidle')
            
            # 额外等待确保动态内容加载完成
            await asyncio.sleep(3)
            
            # 获取并解析SKU信息
            sku_info = await self._get_sku_content()

            # 获取页面标题
            title = await self.page.title()

            result = {
                'order_id': order_id,
                'url': url,
                'title': title,
                'sku_info': sku_info,  # 包含解析后的规格信息
                'spec_name': sku_info.get('spec_name', '') if sku_info else '',
                'spec_value': sku_info.get('spec_value', '') if sku_info else '',
                'quantity': sku_info.get('quantity', '') if sku_info else '',  # 数量
                'amount': sku_info.get('amount', '') if sku_info else '',      # 金额
                'order_status': sku_info.get('order_status', '') if sku_info else '',  # 订单状态
                'order_status_title': sku_info.get('order_status_title', '') if sku_info else '',  # 订单状态标题
                'order_main_title': sku_info.get('order_main_title', '') if sku_info else '',  # 主要状态标题（用于兼容性）
                'timestamp': time.time(),
                'from_cache': False,  # 标记数据来源
                'data_source': 'playwright'  # 标记数据来源为Playwright
            }

            logger.info(f"Playwright方式获取订单详情成功: {order_id}")
            if sku_info:
                logger.info(f"规格信息 - 名称: {result['spec_name']}, 值: {result['spec_value']}")
                logger.info(f"数量: {result['quantity']}, 金额: {result['amount']}")
                if result['order_status']:
                    logger.info(f"订单状态: {result['order_status']}")
            return result
            
        except Exception as e:
            logger.error(f"Playwright方式获取订单详情失败: {e}")
            return None

    def _parse_sku_content(self, sku_content: str) -> Dict[str, str]:
        """
        解析SKU内容，根据冒号分割规格名称和规格值

        Args:
            sku_content: 原始SKU内容字符串

        Returns:
            包含规格名称和规格值的字典，如果解析失败则返回空字典
        """
        try:
            if not sku_content or ':' not in sku_content:
                logger.warning(f"SKU内容格式无效或不包含冒号: {sku_content}")
                return {}

            # 根据冒号分割
            parts = sku_content.split(':', 1)  # 只分割第一个冒号

            if len(parts) == 2:
                spec_name = parts[0].strip()
                spec_value = parts[1].strip()

                if spec_name and spec_value:
                    result = {
                        'spec_name': spec_name,
                        'spec_value': spec_value
                    }
                    logger.info(f"SKU解析成功 - 规格名称: {spec_name}, 规格值: {spec_value}")
                    return result
                else:
                    logger.warning(f"SKU解析失败，规格名称或值为空: 名称='{spec_name}', 值='{spec_value}'")
                    return {}
            else:
                logger.warning(f"SKU内容分割失败: {sku_content}")
                return {}

        except Exception as e:
            logger.error(f"解析SKU内容异常: {e}")
            return {}

    async def _get_sku_content(self) -> Optional[Dict[str, str]]:
        """获取并解析SKU内容，包括规格、数量、金额和订单状态"""
        try:
            # 检查浏览器状态
            if not await self._check_browser_status():
                logger.error("浏览器状态异常，无法获取SKU内容")
                return {}

            result = {}

            # 获取所有 sku--u_ddZval 元素
            sku_selector = '.sku--u_ddZval'
            sku_elements = await self.page.query_selector_all(sku_selector)

            logger.info(f"找到 {len(sku_elements)} 个 sku--u_ddZval 元素")
            print(f"🔍 找到 {len(sku_elements)} 个 sku--u_ddZval 元素")

            # 获取金额信息
            amount_selector = '.boldNum--JgEOXfA3'
            amount_element = await self.page.query_selector(amount_selector)
            amount = ''
            if amount_element:
                amount_text = await amount_element.text_content()
                if amount_text:
                    amount = amount_text.strip()
                    logger.info(f"找到金额: {amount}")
                    print(f"💰 金额: {amount}")
                    result['amount'] = amount
            else:
                logger.warning("未找到金额元素")
                print("⚠️ 未找到金额信息")

            # 获取订单状态信息
            await self._get_order_status(result)

            # 处理 sku--u_ddZval 元素
            if len(sku_elements) == 2:
                # 有两个元素：第一个是规格，第二个是数量
                logger.info("检测到两个 sku--u_ddZval 元素，第一个为规格，第二个为数量")
                print("📋 检测到两个元素：第一个为规格，第二个为数量")

                # 处理规格（第一个元素）
                spec_content = await sku_elements[0].text_content()
                if spec_content:
                    spec_content = spec_content.strip()
                    logger.info(f"规格原始内容: {spec_content}")
                    print(f"🛍️ 规格原始内容: {spec_content}")

                    # 解析规格内容
                    parsed_spec = self._parse_sku_content(spec_content)
                    if parsed_spec:
                        result.update(parsed_spec)
                        print(f"📋 规格名称: {parsed_spec['spec_name']}")
                        print(f"📝 规格值: {parsed_spec['spec_value']}")

                # 处理数量（第二个元素）
                quantity_content = await sku_elements[1].text_content()
                if quantity_content:
                    quantity_content = quantity_content.strip()
                    logger.info(f"数量原始内容: {quantity_content}")
                    print(f"📦 数量原始内容: {quantity_content}")

                    # 从数量内容中提取数量值（使用冒号分割，取后面的值）
                    if ':' in quantity_content:
                        quantity_value = quantity_content.split(':', 1)[1].strip()
                        # 去掉数量值前面的 'x' 符号（如 "x2" -> "2"）
                        if quantity_value.startswith('x'):
                            quantity_value = quantity_value[1:]
                        result['quantity'] = quantity_value
                        logger.info(f"提取到数量: {quantity_value}")
                        print(f"🔢 数量: {quantity_value}")
                    else:
                        # 去掉数量值前面的 'x' 符号（如 "x2" -> "2"）
                        if quantity_content.startswith('x'):
                            quantity_content = quantity_content[1:]
                        result['quantity'] = quantity_content
                        logger.info(f"数量内容无冒号，直接使用: {quantity_content}")
                        print(f"🔢 数量: {quantity_content}")

            elif len(sku_elements) == 1:
                # 只有一个元素：判断是否包含"数量"
                logger.info("检测到一个 sku--u_ddZval 元素，判断是规格还是数量")
                print("📋 检测到一个元素，判断是规格还是数量")

                content = await sku_elements[0].text_content()
                if content:
                    content = content.strip()
                    logger.info(f"元素原始内容: {content}")
                    print(f"🛍️ 元素原始内容: {content}")

                    if '数量' in content:
                        # 这是数量信息
                        logger.info("判断为数量信息")
                        print("📦 判断为数量信息")

                        if ':' in content:
                            quantity_value = content.split(':', 1)[1].strip()
                            # 去掉数量值前面的 'x' 符号（如 "x2" -> "2"）
                            if quantity_value.startswith('x'):
                                quantity_value = quantity_value[1:]
                            result['quantity'] = quantity_value
                            logger.info(f"提取到数量: {quantity_value}")
                            print(f"🔢 数量: {quantity_value}")
                        else:
                            # 去掉数量值前面的 'x' 符号（如 "x2" -> "2"）
                            if content.startswith('x'):
                                content = content[1:]
                            result['quantity'] = content
                            logger.info(f"数量内容无冒号，直接使用: {content}")
                            print(f"🔢 数量: {content}")
                    else:
                        # 这是规格信息
                        logger.info("判断为规格信息")
                        print("📋 判断为规格信息")

                        parsed_spec = self._parse_sku_content(content)
                        if parsed_spec:
                            result.update(parsed_spec)
                            print(f"📋 规格名称: {parsed_spec['spec_name']}")
                            print(f"📝 规格值: {parsed_spec['spec_value']}")
            else:
                logger.warning(f"未找到或找到异常数量的 sku--u_ddZval 元素: {len(sku_elements)}")
                print(f"⚠️ 未找到或找到异常数量的元素: {len(sku_elements)}")

                # 如果没有找到sku--u_ddZval元素，设置默认数量为1
                if len(sku_elements) == 0:
                    result['quantity'] = '1'
                    logger.info("未找到sku--u_ddZval元素，数量默认设置为1")
                    print("📦 数量默认设置为: 1")

                # 尝试获取页面的所有class包含sku的元素进行调试
                all_sku_elements = await self.page.query_selector_all('[class*="sku"]')
                if all_sku_elements:
                    logger.info(f"找到 {len(all_sku_elements)} 个包含'sku'的元素")
                    for i, element in enumerate(all_sku_elements):
                        class_name = await element.get_attribute('class')
                        text_content = await element.text_content()
                        logger.info(f"SKU元素 {i+1}: class='{class_name}', text='{text_content}'")

            # 确保数量字段存在，如果不存在则设置为1
            if 'quantity' not in result:
                result['quantity'] = '1'
                logger.info("未获取到数量信息，默认设置为1")
                print("📦 数量默认设置为: 1")

            # 打印最终结果
            if result:
                logger.info(f"最终解析结果: {result}")
                print("✅ 解析结果:")
                for key, value in result.items():
                    print(f"   {key}: {value}")
                return result
            else:
                logger.warning("未能解析到任何有效信息")
                print("❌ 未能解析到任何有效信息")
                # 即使没有其他信息，也要返回默认数量
                return {'quantity': '1'}

        except Exception as e:
            logger.error(f"获取SKU内容失败: {e}")
            return {}

    async def _get_order_status(self, result: Dict[str, str]) -> None:
        """获取订单状态信息"""
        try:
            # 尝试多种可能的订单状态选择器
            status_selectors = [
                '.title--ZOkK1WnM span',  # 根据您提供的HTML结构
                '.title--ZOkK1WnM',
                '[class*="title--"] span',
                '[class*="title--"]',
                '.order-status span',
                '.order-status',
                '[data-spm-anchor-id] span',
                '[data-spm-anchor-id]'
            ]
            
            order_status = ''
            order_status_title = ''
            
            for selector in status_selectors:
                try:
                    status_element = await self.page.query_selector(selector)
                    if status_element:
                        status_text = await status_element.text_content()
                        if status_text and status_text.strip():
                            order_status = status_text.strip()
                            order_status_title = status_text.strip()
                            logger.info(f"通过选择器 '{selector}' 找到订单状态: {order_status}")
                            print(f"📋 订单状态: {order_status}")
                            break
                except Exception as e:
                    logger.debug(f"选择器 '{selector}' 查找失败: {e}")
                    continue
            
            # 如果没有找到，尝试搜索包含常见状态关键词的元素
            if not order_status:
                status_keywords = [
                    '已发货', '待确认收货', '待付款', '买家已付款', '请尽快发货',
                    '交易成功', '交易完成', '已收货', '已评价', '退款中'
                ]
                
                for keyword in status_keywords:
                    try:
                        # 使用XPath查找包含关键词的元素
                        xpath = f"//*[contains(text(), '{keyword}')]"
                        status_elements = await self.page.query_selector_all(f'xpath={xpath}')
                        
                        for element in status_elements:
                            status_text = await element.text_content()
                            if status_text and keyword in status_text:
                                order_status = status_text.strip()
                                order_status_title = status_text.strip()
                                logger.info(f"通过关键词 '{keyword}' 找到订单状态: {order_status}")
                                print(f"📋 订单状态 (关键词匹配): {order_status}")
                                break
                        
                        if order_status:
                            break
                    except Exception as e:
                        logger.debug(f"关键词 '{keyword}' 搜索失败: {e}")
                        continue
            
            # 如果仍然没有找到，尝试获取页面中所有可能的状态文本
            if not order_status:
                try:
                    # 获取所有div元素的文本内容，查找可能的状态信息
                    all_divs = await self.page.query_selector_all('div')
                    for div in all_divs:
                        try:
                            div_text = await div.text_content()
                            if div_text and any(keyword in div_text for keyword in ['已发货', '待确认', '待付款', '已付款', '交易']):
                                # 获取div的class属性用于调试
                                div_class = await div.get_attribute('class')
                                logger.debug(f"找到可能的状态div: class='{div_class}', text='{div_text.strip()}'")
                                
                                if not order_status and len(div_text.strip()) < 50:  # 避免获取过长的文本
                                    order_status = div_text.strip()
                                    order_status_title = div_text.strip()
                                    logger.info(f"通过div遍历找到订单状态: {order_status}")
                                    print(f"📋 订单状态 (div遍历): {order_status}")
                                    break
                        except:
                            continue
                except Exception as e:
                    logger.debug(f"遍历div元素失败: {e}")
            
            # 将状态信息添加到结果中
            if order_status:
                result['order_status'] = order_status
                result['order_status_title'] = order_status_title
                result['order_main_title'] = order_status  # 为了兼容pending_payment_scheduler的检查逻辑
                logger.info(f"成功获取订单状态: {order_status}")
            else:
                logger.warning("未能获取到订单状态信息")
                print("⚠️ 未能获取到订单状态信息")
                
                # 输出页面内容用于调试
                try:
                    page_content = await self.page.content()
                    # 查找可能包含状态的HTML片段
                    if 'title--' in page_content:
                        import re
                        title_matches = re.findall(r'<[^>]*class="[^"]*title--[^"]*"[^>]*>([^<]+)</[^>]*>', page_content)
                        if title_matches:
                            logger.info(f"页面中找到的title--相关内容: {title_matches}")
                except Exception as e:
                    logger.debug(f"获取页面内容用于调试失败: {e}")
                    
        except Exception as e:
            logger.error(f"获取订单状态失败: {e}")

    async def _check_browser_status(self) -> bool:
        """检查浏览器状态是否正常"""
        try:
            if not self.browser or not self.context or not self.page:
                logger.warning("浏览器组件不完整")
                return False
            
            # 检查页面是否仍然有效
            try:
                await self.page.evaluate("() => document.readyState")
                return True
            except Exception as e:
                logger.warning(f"页面状态检查失败: {e}")
                return False
        except Exception as e:
            logger.error(f"浏览器状态检查异常: {e}")
            return False

    async def close(self):
        """关闭浏览器"""
        try:
            if self.page:
                await self.page.close()
            if self.context:
                await self.context.close()
            if self.browser:
                await self.browser.close()
            logger.info("浏览器已关闭")
        except Exception as e:
            logger.error(f"关闭浏览器失败: {e}")

    async def __aenter__(self):
        """异步上下文管理器入口"""
        await self.init_browser()
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        """异步上下文管理器出口"""
        await self.close()


# 便捷函数
async def fetch_order_detail_simple(order_id: str, cookie_string: str = None, headless: bool = True, use_api: bool = True) -> Optional[Dict[str, Any]]:
    """
    简单的订单详情获取函数

    Args:
        order_id: 订单ID
        cookie_string: Cookie字符串，如果不提供则使用默认值
        headless: 是否无头模式
        use_api: 是否优先使用API方式，默认True

    Returns:
        订单详情字典或None
    """
    fetcher = OrderDetailFetcher(cookie_string)
    try:
        # 如果使用API方式，不需要初始化浏览器
        if use_api:
            api_result = await fetcher.fetch_order_detail_via_api(order_id)
            if api_result:
                return api_result
            # API失败，尝试Playwright方式
            logger.warning(f"API方式失败，尝试Playwright方式获取订单详情: {order_id}")
        
        # 使用Playwright方式需要初始化浏览器
        if await fetcher.init_browser(headless=headless):
            return await fetcher.fetch_order_detail_via_playwright(order_id)
    finally:
        await fetcher.close()
    return None


# 测试代码
if __name__ == "__main__":
    async def test():
        # 测试订单ID
        test_order_id = "2856024697612814489"
        
        print(f"🔍 开始获取订单详情: {test_order_id}")
        
        result = await fetch_order_detail_simple(test_order_id, headless=False)
        
        if result:
            print("✅ 订单详情获取成功:")
            print(f"📋 订单ID: {result['order_id']}")
            print(f"🌐 URL: {result['url']}")
            print(f"📄 页面标题: {result['title']}")
            print(f"🛍️ SKU内容: {result['sku_content']}")
        else:
            print("❌ 订单详情获取失败")
    
    # 运行测试
    asyncio.run(test())
